package com.lindroy.androidplayer.viewmodel

import androidx.lifecycle.MutableLiveData
import com.lindroy.androidplayer.base.viewmodel.BaseViewModel
import com.lindroy.androidplayer.extensions.request
import com.lindroy.androidplayer.extensions.yes
import com.lindroy.androidplayer.logic.model.CoinHistoryResp
import com.lindroy.androidplayer.logic.model.CoinPersonalResp
import com.lindroy.androidplayer.logic.model.CoinRankingResp
import com.lindroy.androidplayer.logic.network2.state.ResultState
import com.lindroy.androidplayer.logic.network2.apiService
import com.lindroy.androidplayer.logic.network2.statecallback.ListDataState

/**
 * @author Lin
 * @date 2021/4/27
 * @function 积分模块
 */
class CoinViewModel : BaseViewModel() {
    private var historyPageNo = 1
    private var rankingPageNo = 1

    val coinHistoryState: MutableLiveData<ListDataState<CoinHistoryResp>> = MutableLiveData()

    val coinRankingState: MutableLiveData<ListDataState<CoinRankingResp>> = MutableLiveData()

    val coinInfoState: MutableLiveData<ResultState<CoinPersonalResp>> = MutableLiveData()


    /**
     * 积分记录
     */
    fun reqCoinHistory(isRefresh: Boolean) {
        isRefresh.yes { historyPageNo = 1 }
        request({ apiService.getCoinHistory(historyPageNo) }, {
            coinHistoryState.value = ListDataState(
                success = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.datas
            )
            historyPageNo++
        }, {
            coinHistoryState.value = ListDataState(
                success = false,
                isRefresh = isRefresh,
                errMessage = it.errorMsg,
                listData = arrayListOf()
            )
        })
    }

    fun reqCoinRanking(isRefresh: Boolean){
        isRefresh.yes { rankingPageNo = 1 }
        request({ apiService.getCoinRanking(rankingPageNo)},{
            coinRankingState.value = ListDataState(
                success = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.datas
            )
            rankingPageNo++
        },{
            coinRankingState.value = ListDataState(
                success = false,
                isRefresh = isRefresh,
                errMessage = it.errorMsg,
                listData = arrayListOf()
            )
        })
    }

    /**
     * 获取个人积分信息
     */
    fun reqCoinInfo() {
        request({ apiService.getPersonalCoin() }, coinInfoState)
    }
}